package com.zjdiepu.www.manage.api.base;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.AttachmentSort;
import com.zjdiepu.www.base.enums.type.AttachmentType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.commpent.mapper.base.OtherAttachmentsVoMapper;
import com.zjdiepu.www.ibiz.base.IOtherAttachmentsService;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.model.base.ext.OtherAttachmentsExt;
import com.zjdiepu.www.util.CachedEnums;

/**
 * 附件信息Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月03日 11时48分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "OtherAttachmentsController", produces="application/json;charset=UTF-8")
@Api(tags = {"附件信息"}, produces="application/json;charset=UTF-8")
public class OtherAttachmentsController extends BaseController {
    @Resource
    private IOtherAttachmentsService otherAttachmentsService;
    @Resource
    private OtherAttachmentsVoMapper otherAttachmentsVoMapper;
    @Resource
    private IQiniuFileService qiniuFileService;
    /**
     * @author xiongxiaotun <br/>
     * @Title: queryOtherAttachments  <br/>
     * @Description: 附件获取 <br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "附件获取", response = OtherAttachments.class, httpMethod="POST", tags={"附件获取"})
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "id", value = "业务ID", paramType="query", required = true, example="1"),
    	@ApiImplicitParam(name = "customerId", value = "客户ID", paramType="query", required = false, example="2"),
    	@ApiImplicitParam(name = "modeId", value = "模块ID", paramType="query", required = false, example="23234235235325325"),
    	@ApiImplicitParam(name = "subDataId", value = "字表ID", paramType="query", required = false, example="23234235235325325"),
    	@ApiImplicitParam(name = "includeFileLabels", value = "包含的标签", paramType="query", required = false, example="23234235235325325"),
    	@ApiImplicitParam(name = "excludeFileLabels", value = "排除的标签", paramType="query", required = false, example="23234235235325325")
    })
    @RequestMapping(value = "queryOtherAttachments", method = RequestMethod.POST)
    public ApiResponse queryOtherAttachments(String id, String customerId, String modeId, String subDataId, String includeFileLabels, String excludeFileLabels) {
    	if (!org.apache.commons.lang3.StringUtils.isNoneBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	Map<String, Object> response = new LinkedHashMap<String, Object>();
    	OtherAttachmentsExt otherAttachmentsExt = new OtherAttachmentsExt();
    	otherAttachmentsExt.setBaseWhere();
    	otherAttachmentsExt.withOutPage();
    	otherAttachmentsExt.setDataid(id);// 所属业务
    	if(StringUtils.isNotBlank(modeId)) {
    		otherAttachmentsExt.setModeId(modeId); // 所处阶段
    	}
    	otherAttachmentsExt.setSubDataid(subDataId);
    	if(StringUtils.isNotBlank(customerId)) {
    		otherAttachmentsExt.setCustomerId(customerId);// 所属客户
    	}
    	otherAttachmentsExt.setOrderSql("`FILE_LABEL` ASC");
    	List<String> includeFileLabels_ = new ArrayList<String>();
    	if(StringUtils.isNotBlank(includeFileLabels)) {
    		includeFileLabels_ = Arrays.asList(includeFileLabels.split(","));
    	}
    	List<String> excludeFileLabels_ = new ArrayList<String>();
    	if(StringUtils.isNotBlank(excludeFileLabels)) {
    		excludeFileLabels_ = Arrays.asList(excludeFileLabels.split(","));
    	}
    	otherAttachmentsExt.setIncludeFileLabels(includeFileLabels_);
    	otherAttachmentsExt.setExcludeFileLabels(excludeFileLabels_);
    	List<OtherAttachments> attachments = otherAttachmentsService.selectByExt(otherAttachmentsExt);
    	// 附件添加
    	Map<String, LinkedHashSet<OtherAttachments>> otherAttachmentses = CollectionInitUtil.emptyMap();
    	for (OtherAttachments attachment : attachments) {
    		otherAttachmentsVoMapper.mapper(attachment);
    		String ossPath = attachment.getOssPath();
    		if(StringUtils.isNotBlank(ossPath)) {
    			if(AttachmentType.IMAGE.getCode().equals(attachment.getAttachmentType())){
	    			String url = qiniuFileService.getURL(ossPath + SystemConsts.THUMBNAIL_SUBBFIX);
	    			attachment.setUrl(url);
    			}
    			String bigUrl = qiniuFileService.getURL(ossPath);
    			attachment.setBigUrl(bigUrl);
    		}
    		String attachmentSort = attachment.getAttachmentSort();
    		AttachmentSort attachmentSortEnum = CachedEnums.getByCode(
    				attachmentSort, AttachmentSort.class);
    		if (null != attachmentSortEnum) {
    			addAttachment(attachmentSortEnum.toString(),attachment, otherAttachmentses);
    		}
    	}
    	response.put("otherAttachments", otherAttachmentses);
    	return ApiResponse.success(response);
    }
    
    /**
	 * @author xiongxiaotun <br/>
	 * @Title: addAttachment <br/>
	 * @Description: 添加附件 <br/>
	 * @param attachmentSort 附件类别
	 * @param otherAttachments 待添加附件
	 * @param otherAttachmentses 附件容器
	 * @version V1.0  <br/>
	 */
	public static void addAttachment(String attachmentSort, OtherAttachments otherAttachments,Map<String, LinkedHashSet<OtherAttachments>> otherAttachmentses) {
		if(null == otherAttachments || StringUtils.isBlank(attachmentSort)) {
			return;
		}
		if(null == otherAttachmentses) {
			otherAttachmentses = CollectionInitUtil.emptyMap();
		}
		LinkedHashSet<OtherAttachments> otherAttachments_ = otherAttachmentses.get(attachmentSort);
		if(null == otherAttachments_) {
			otherAttachments_ = new LinkedHashSet<OtherAttachments>();
		}
		otherAttachments_.add(otherAttachments);
		otherAttachmentses.put(attachmentSort, otherAttachments_);
	}

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增附件信息 <br/>
     * @param otherAttachments
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增附件信息", response = OtherAttachments.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute OtherAttachments otherAttachments,String upDelete) {
    	AbstractSysUser currentUser = getCurrentUser();
    	otherAttachments.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	otherAttachments.setModifierName(currentUser.getName());
        otherAttachmentsService.saveUpdateAndDelete(otherAttachments, OperateType.add,"0");
        otherAttachmentsVoMapper.mapper(otherAttachments);
        return ApiResponse.success(otherAttachments);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除附件信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除附件信息", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	otherAttachmentsService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用附件信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用附件信息", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	otherAttachmentsService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用附件信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用附件信息", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	otherAttachmentsService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改附件信息 <br/>
     * @param otherAttachments
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改附件信息", response = OtherAttachments.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute OtherAttachments otherAttachments) {
    	AbstractSysUser currentUser = getCurrentUser();
    	otherAttachments.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	otherAttachments.setModifierName(currentUser.getName());
    	otherAttachmentsService.saveUpdateAndDelete(otherAttachments, OperateType.edit,null);
    	otherAttachmentsVoMapper.mapper(otherAttachments);
        return ApiResponse.success(otherAttachments);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询附件信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询附件信息", response = OtherAttachments.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       OtherAttachments otherAttachments = otherAttachmentsService.selectById(id);
       if(null == otherAttachments) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(otherAttachments);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询附件信息 <br/>
     * @param otherAttachmentsExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询附件信息",response = OtherAttachments.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute OtherAttachmentsExt otherAttachmentsExt){
        otherAttachmentsExt.notDeleted();
        PageVo page = getPage(otherAttachmentsExt);
        int records = otherAttachmentsService.countByExt(otherAttachmentsExt);
        page.setRecords(records);
        if (records > 0) {
            List<OtherAttachments> otherAttachmentss = otherAttachmentsService.selectByExt(otherAttachmentsExt);
            page.setRows(otherAttachmentss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
